package com.xly.webclick.base

import android.annotation.SuppressLint
import android.app.Activity
import android.databinding.ViewDataBinding
import android.graphics.Color
import android.os.Bundle
import android.os.Message
import android.text.TextUtils
import android.util.Log
import android.view.View
import android.view.ViewGroup
import android.webkit.WebChromeClient
import android.webkit.WebSettings
import android.webkit.WebView
import android.webkit.WebViewClient

import com.xly.webclick.utils.SpUtils
import com.xly.webclick.utils.StringUtils
import com.zyao89.view.zloading.ZLoadingDialog
import com.zyao89.view.zloading.Z_TYPE

import org.json.JSONException
import org.json.JSONObject

import java.io.BufferedReader
import java.io.IOException
import java.io.InputStream
import java.io.InputStreamReader
import java.lang.ref.WeakReference
import java.net.HttpURLConnection
import java.net.URL
import java.net.URLConnection

import io.reactivex.Observable
import io.reactivex.ObservableOnSubscribe
import io.reactivex.android.schedulers.AndroidSchedulers

/**
 * Created by xuleyuan on 2018/8/10
 */

abstract class BaseViewModel (outView: Activity?) {

    var dialog: ZLoadingDialog? = null

    val view: WeakReference<Activity?> = WeakReference(outView)

    val shengCode: String
        get() = ""

     fun getActivity(): Activity {
        return view.get()!!
    }

    abstract fun onResume()

    fun onCreate(savedInstanceState: Bundle?) {
        dialog = ZLoadingDialog(getActivity())
        dialog!!.setLoadingBuilder(Z_TYPE.PAC_MAN)//设置类型
                .setLoadingColor(Color.BLACK)//颜色
                .setHintText("正在加载必要资源...")
                .setHintTextSize(16f) // 设置字体大小 dp
                .setHintTextColor(Color.GRAY)  // 设置字体颜色
                .setDurationTime(0.5) // 设置动画时间百分比 - 0.5倍
                .setDialogBackgroundColor(Color.parseColor("#CCFFFFFF")) // 设置背景色，默认白色
        //        if (TextUtils.isEmpty(SpUtils.getString(SpUtils.ATV_IP)) || TextUtils.isEmpty(SpUtils.getString(SpUtils.ATV_ADDRESS))) {
        //            dialog.show();
        //            String a = getNetIp();
        //            WebView view = new WebView(getView());
        //            view.setVisibility(View.INVISIBLE);
        //            view.setLayoutParams(new ViewGroup.LayoutParams(-1, -1));
        //            ((ViewGroup)getView().getWindow().getDecorView()).addView(view);
        //            initWebView(view);
        //        } else {
        initData(savedInstanceState)
        //        }

    }

    @SuppressLint("SetJavaScriptEnabled")
    private fun initWebView(paramWebView: WebView) {
        val localWebSettings = paramWebView.settings
        localWebSettings.defaultTextEncodingName = "GBK"
        localWebSettings.javaScriptCanOpenWindowsAutomatically = true
        localWebSettings.javaScriptEnabled = true
        localWebSettings.domStorageEnabled = true
        localWebSettings.builtInZoomControls = true
        localWebSettings.useWideViewPort = true
        localWebSettings.loadWithOverviewMode = true
        localWebSettings.userAgentString = ""
        paramWebView.webViewClient = object : WebViewClient() {
            override fun onPageFinished(webView: WebView, paramAnonymousString: String) {
                super.onPageFinished(webView, paramAnonymousString)
                webView.loadUrl("javascript:" + StringUtils.getJson("ip.js", getActivity()))
                webView.evaluateJavascript("GetIP_TaoBao()") { it ->
                    var data: String? = null
                    data = it.replace("\\", "")
                    data = it.substring(1, it.length - 1)
                    val localMessage = Message.obtain()
                    localMessage.obj = data
                    localMessage.what = 5
                    Observable.create(ObservableOnSubscribe<String> { emitter -> emitter.onNext(data) })
                            .observeOn(AndroidSchedulers.mainThread()).subscribeOn(AndroidSchedulers.mainThread())
                            .subscribe { o -> operateAddressData(o) }
                    //                    LoginActivity.this.handler.sendMessage(localMessage);
                }
            }
        }
        paramWebView.webChromeClient = object : WebChromeClient() {

        }
        paramWebView.loadUrl("http://ip.taobao.com/ipSearch.html")
    }

    fun operateAddressData(data: String) {
        val str2 = ""
        val str3 = ""
        try {
            val jsonObject = JSONObject(data)
            val str7 = jsonObject.getString("ip").toString()
            val str4 = jsonObject.getString("sheng").toString()
            val str5 = jsonObject.getString("shi").toString()
            //            paramAnonymousMessage = jsonObject.getString("isp").toString();
            //            String str6 = str7 + " " + str4 + str5 + " " + paramAnonymousMessage;
            //            String str1 = str2;
            //            paramAnonymousMessage = str3;
            //            if (str7.length() > 0)
            //            {
            //                str1 = str2;
            //                paramAnonymousMessage = str3;
            //                if (str4.length() > 0)
            //                {
            //                    str1 = str2;
            //                    paramAnonymousMessage = str3;
            //                    if (str5.length() > 0)
            //                    {
            //                        String address = StringUtils.getJson("ShengShiList.txt", getView());
            //                        str1 = LoginActivity.this.methods.GetShengCode(paramAnonymousMessage, str4);
            //                        paramAnonymousMessage = LoginActivity.this.methods.GetShiCode(paramAnonymousMessage, str5, str1);
            //                        paramBundle.putString("userIP", str6);
            //                        paramBundle.putString("sheng_tb", str4);
            //                        paramBundle.putString("shi_tb", str5);
            //                        paramBundle.putString("shengCode_tb", str1);
            //                        paramBundle.putString("shiCode_tb", paramAnonymousMessage);
            //                        paramBundle.commit();
            //                    }
            //                }
            //            }
            //            LoginActivity.this.methods.syslog("userIP=" + str6);
            //            LoginActivity.this.methods.syslog("sheng_tb=" + str4);
            //            LoginActivity.this.methods.syslog("shi_tb=" + str5);
            //            LoginActivity.this.methods.syslog("shengCode_tb=" + str1);
            //            LoginActivity.this.methods.syslog("shiCode_tb=" + paramAnonymousMessage);
            return
        } catch (paramAnonymousMessage: JSONException) {
            paramAnonymousMessage.printStackTrace()
            Log.d("信息", "Err1010=" + paramAnonymousMessage.message)
            return
        }

    }


    override fun equals(obj: Any?): Boolean {
        return super.equals(obj)
    }

    protected abstract fun initData(savedInstanceState: Bundle?)


    open fun onDestroy() {

    }

    open fun onStop() {

    }

    open fun onPause() {

    }

    open fun onRestart() {

    }

    open fun onWindowFocusChanged(hasFocus: Boolean) {

    }

    fun goback() {
        view.get()!!.finish()
    }

    override fun hashCode(): Int {
        var result = dialog?.hashCode() ?: 0
        result = 31 * result + view.hashCode()
        return result
    }

    companion object {

        //builder.append(line).append("\n");
        //                int shi = builder.indexOf("市",end);
        //                int qu = builder.indexOf("市",end);
        //                ip = builder.substring(start + 1, end);
        //                sheng = builder.substring(builder.indexOf("来自：",end),)
        val netIp: String?
            get() {
                val ip = ""
                val sheng = ""
                val shi = ""
                var inStream: InputStream? = null
                try {
                    val infoUrl = URL("http://ip138.com")
                    val connection = infoUrl.openConnection()
                    val httpConnection = connection as HttpURLConnection
                    val responseCode = httpConnection.responseCode
                    if (responseCode == HttpURLConnection.HTTP_OK) {
                        inStream = httpConnection.inputStream
                        val reader = BufferedReader(InputStreamReader(inStream!!, "gb2312"))
                        val builder = StringBuilder()
                        var line: String? = null
                        do {
                            val line = reader.readLine()
                            builder.append(line)
                        } while (line != null)
                        inStream.close()
                        val start = builder.indexOf("[")
                        val end = builder.indexOf("]")

                        return ip
                    }
                } catch (e: IOException) {
                    e.printStackTrace()
                }

                return null
            }
    }

}
